package com.designpattern.test;

import cn.hutool.core.thread.ConcurrencyTester;
import cn.hutool.core.thread.ThreadUtil;
import com.designpattern.creating.abstractfactory.AbstractFactory;
import com.designpattern.creating.abstractfactory.FactoryInterFace;
import com.designpattern.creating.builder.ObjForBuilder;
import com.designpattern.creating.builder.ObjWithLombok;
import com.designpattern.creating.factory.Factory;
import com.designpattern.creating.factory.BizInterFace;
import com.designpattern.creating.origion.BizService;
import com.designpattern.creating.origion.ObjForOrigin;
import com.designpattern.creating.singleton.Singleton_CAS;
import com.designpattern.creating.singleton.Singleton_doubleLock;
import com.designpattern.creating.singleton.Singleton_insideClass;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

@Slf4j
public class CreatingTester {

    @Test
    public void factoryTest(){
        Factory factory = new Factory();
        BizInterFace bizService1 = factory.getBizService(1);
        BizInterFace bizService2 = factory.getBizService(2);

        bizService1.biz1();
        bizService2.biz1();
    }

    @Test
    public void abstractFactoryTest(){
        FactoryInterFace factory1 = AbstractFactory.getFactory(1);
        factory1.getBizService(1).biz1();

        FactoryInterFace factory2 = AbstractFactory.getFactory(2);
        factory2.getBizService(1).biz1();
    }

    @Test
    public void builderTest(){
        ObjForBuilder objForBuilder = new ObjForBuilder().addStr1("字段1").addStr2("字段2");
        log.info(objForBuilder.toString());

        ObjWithLombok objWithLombok = ObjWithLombok.builder().str1("字段1").str2("字段2").build();
        log.info(objWithLombok.toString());
        objWithLombok = objWithLombok.toBuilder().str2("字段2变更").build();
        log.info(objWithLombok.toString());
    }

    @Test
    public void originTest(){
        BizService bizService = new BizService();
        ObjForOrigin cloned = bizService.getObj();
        log.info(cloned.toString());
    }

    @Test
    public void singletonTest(){

        ConcurrencyTester tester = ThreadUtil.concurrencyTest(300, () -> {
            Singleton_doubleLock instance = Singleton_doubleLock.getInstance();
            log.info("thread: {}, obj: {}",Thread.currentThread().getId(),instance.toString());
        });

        // 获取总的执行时间，单位毫秒
        log.info(tester.getInterval() + "ms");
    }
}
